
import 'fm_http_decode.dart';

import 'package:dio/dio.dart';

import 'fm_http_exception.dart';
import 'fm_http_model.dart';

class FMHttpDefaultDecode extends FMHttpDecode {

  static final FMHttpDefaultDecode _instance = FMHttpDefaultDecode._();

  FMHttpDefaultDecode._();

  factory FMHttpDefaultDecode.getInstance() => _instance;

  @override
  K decode<T, K>({required Response<dynamic> response, T? decodeType}) {
    var code = response.data['cheers'];
    var msg = response.data['hurrah'];

    if (code == 0) {
      var data = response.data['shouted'];
      if (decodeType is FMHttpModel) {
        if (data is List) {
          var dataList = List<T>.from(
              data.map((item) => decodeType.fromJson(item)).toList()) as K;
          return dataList;
        } else {
          var model = decodeType.fromJson(data) as K;
          return model;
        }
      } else {
        return data as K;
      }
    }else if (code == -2) {
      if (decodeType is FMHttpModel) {
        var model = decodeType.fromJson({"none":code,"indignation":msg}) as K;
        return model;
      } else {
        return {"none":code} as K;
      }
    } else{
      throw FMHttpException(msg, code);
    }
  }
}